package org.dftproject.patml.ui;

import org.dftproject.genesis.data.genealogy.GenealogyUtils;
import org.dftproject.genesis.data.genealogy.ISource;
import org.dftproject.genesis.ui.citations.ICitation;
import org.dftproject.genesis.ui.citations.ICitationFormatter;
import org.dftproject.genesis.ui.editors.BrowserEditor;
import org.dftproject.genesis.ui.editors.BrowserEditorInput;
import org.dftproject.genesis.ui.figures.IHyperlinkListener;
import org.dftproject.patml.data.PatmlSite;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

public class PatmlCitationFormatter implements ICitationFormatter {

	public void format(ICitation citation, ISource source) {
		PatmlSite site = (PatmlSite) GenealogyUtils.getValue(source, "site", PatmlSite.class);
		
		final String url = site.getUrl();
		citation.addHyperlink(url, new IHyperlinkListener() {

			public void linkActivated(Object data, int stateMask) {
				IWorkbench workbench = PlatformUI.getWorkbench();
				IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
				IWorkbenchPage workbenchPage = window.getActivePage();
				try {
					workbenchPage.openEditor(new BrowserEditorInput(url), BrowserEditor.ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID);
				} catch (PartInitException e) {
					MessageDialog.openError(window.getShell(), "Error", "Error opening browser: " + e.getMessage());
				}
			}
				
		}, url);
		
		citation.addText(", " + site.getType() + ".");

		String id = (String) GenealogyUtils.getValue(source, "id", String.class);
		if (id != null) {
			final String personUrl = site.getPersonUrl(id);
			
			citation.addText(" ");
			citation.addHyperlink(id, new IHyperlinkListener() {

				public void linkActivated(Object data, int stateMask) {
					IWorkbench workbench = PlatformUI.getWorkbench();
					IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
					IWorkbenchPage workbenchPage = window.getActivePage();
					try {
						workbenchPage.openEditor(new BrowserEditorInput(personUrl), BrowserEditor.ID, true, IWorkbenchPage.MATCH_INPUT | IWorkbenchPage.MATCH_ID);
					} catch (PartInitException e) {
						MessageDialog.openError(window.getShell(), "Error", "Error opening browser: " + e.getMessage());
					}
				}
				
			}, personUrl);
			citation.addText(".");
		}
	}
	
}
